package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @ClassName UserServiceImpl
 * @Description 用户业务层实现类
 * @Author sld
 * @Date 2024/7/10 16:42
 * Version 1.0
 **/
@Service
public class UserServiceImpl  implements UserService {

    // 微信服务接口
    public static  final String WX_LOGIN_URL =
            "https://api.weixin.qq.com/sns/jscode2session";

    @Resource
    private UserMapper userMapper;

    @Resource
    private WeChatProperties weChatProperties;  // 微信属性对象


    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        /*
         向微信发起登录请求
         */
        // 封装参数
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map); // 发起请求
        JSONObject jsonObject = JSON.parseObject(json); // json转java
        String openid = jsonObject.getString("openid"); // 获取openid
        // 判断登录是否成功
        if(openid==null  || openid.equals("")){  // 登录失败
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED); // 抛出登录失败异常
        }
        User user = userMapper.getByOpenid(openid); // 查询用户是否注册
        if(user == null){  // 用户未注册
            // 自动注册新用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);    // 执行插入数据操作
        }
        return user;
    }
}
